package com.xyzq.cgate.core.component.loadbalance;

import com.google.common.base.Preconditions;
import com.xyzq.cgate.common.enums.LoadBalanceEnum;
import com.xyzq.cgate.common.rule.custom.entity.BalancePiece;
import com.xyzq.cgate.common.rule.custom.entity.LoadBalance;

/**
 * @Description:
 * @author chenchen
 * @date 2019/6/24 9:57
 */
public class RoundRobinSelector implements LoadBalanceSelector {

    private static Integer pos = 0;

    @Override
    public BalancePiece select(LoadBalance loadBalance, String ip) {
        Preconditions.checkNotNull(loadBalance);
        Preconditions.checkNotNull(loadBalance.getData());
        final BalancePiece[] balancePieces = loadBalance.getData();
        int length = balancePieces.length;
        BalancePiece balancePiece = null;
        synchronized(pos) {
             if (pos >= length) {
                 pos = 0;
             }
            balancePiece = balancePieces[pos];
             pos ++;
        }
        return balancePiece;

    }

    @Override
    public String getAlgorithm() {
        return LoadBalanceEnum.ROUND_ROBIN.getName();
    }
}
